import React, { useState } from "react";
import { View, Button, Image, Alert } from "react-native";
import * as ImagePicker from "expo-image-picker";
import { useRouter } from "expo-router";
import Camera from '@/component/TakePhotos/camera';


function CareManage() {
    const [image, setImage] = useState<string | null>(null);
    const router = useRouter();


    // 选择图片（从相机或相册）
    const uploadImage = async () => {
        try {
            // 弹出选择相册或相机
            const result = await ImagePicker.launchImageLibraryAsync({
                mediaTypes: ImagePicker.MediaTypeOptions.Images,
                allowsEditing: true,
                quality: 1,
            });

            if (!result.canceled) {
                console.log(result.assets[0].uri);
                await saveImage(result.assets[0].uri);
            }
        } catch (err) {
            alert("上传照片错误" + err);
        }
    };

    // 保存图片（显示选择的图片）
    const saveImage = async (image: string) => {
        setImage(image);
    };

    // 获取当前时间
    const getCurrentTime = () => {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, "0");
        const day = String(now.getDate()).padStart(2, "0");
        const hours = String(now.getHours()).padStart(2, "0");
        const minutes = String(now.getMinutes()).padStart(2, "0");
        const seconds = String(now.getSeconds()).padStart(2, "0");

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    // 上传图片到后端接口
    const uploadToServer = async () => {
        const formData = new FormData();
        const photoData = {
            treeid: "123",
            treenumber: "123",
            qid: "123",
            location: "123",
            uploader: "123",
            time: getCurrentTime(),
            memo: "rn上传",
            type: "1",
        };

        // 构建FormData
        formData.append("file", {
            uri: image, // React Native中传入的图片uri
            name: "upload.jpg", // 文件名
            type: "image/jpeg", // 文件类型
        });

        // 添加其他参数到formData
        Object.keys(photoData).forEach((key) => {
            formData.append(key, photoData[key]);
        });

        try {
            const response = await fetch(
                "http://192.168.1.11/briefos/photo/archivephotos",
                {
                    method: "POST",
                    body: formData,
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                }
            );

            if (response.ok) {
                const data = await response.json();
                console.log("Upload success:", data);
                Alert.alert("上传成功", "图片上传成功！"); // 提示成功
            } else {
                throw new Error("上传失败");
            }
        } catch (error) {
            console.error("Upload failed:", error);
            Alert.alert("上传失败", "请重试上传图片！"); // 提示失败
        }
    };

   function openCamera(){
     router.push("/camera");
   }

    return (
        <View>
            <Button title="上传图片" onPress={uploadImage} />
            {image && (
                <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
            )}
            <Button title="提交上传" onPress={uploadToServer} />
      <Button title="打开相机" onPress={openCamera}></Button>

        </View>
    );
}

export default CareManage;
